package com.bite.spring.trans.controller;

import com.bite.spring.trans.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private DataSourceTransactionManager transactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @RequestMapping("/registry")
    public Boolean registry(String userName, String password) {
        Integer i = 0;
        // 开启事务
        TransactionStatus transaction = transactionManager.getTransaction(transactionDefinition);
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return false;
        }
        i = userService.insert(userName, password);
        // 回滚
//        transactionManager.rollback(transaction);
        transactionManager.commit(transaction);
        log.info("影响的行数为：" + i);
        return i == 1;
    }
}
